import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core';
import { WebGLService } from 'src/app/services/webgl.service';

@Component({
    selector: 'transform-triangle',
    templateUrl: './transform-triangle.component.html',
    styleUrls: ['./transform-triangle.component.scss']
})
export class TranformTriangleComponent implements OnInit, AfterViewInit, OnDestroy {
    // 顶点着色器
    private vertexShaderSource = `
        attribute vec4 a_Position;
        uniform mat4 u_xformMatrix;
        void main () {
            gl_Position = u_xformMatrix * a_Position;
            gl_PointSize = 10.0;
        }  
    `;
    private fragShaderSource = `
        void main () {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }
    `;

    private ANGLE: number = 0;
    private gl: WebGLRenderingContext;
    private animationId: number;
    
    constructor(private webglService: WebGLService) { }
    ngOnInit() { }
    ngAfterViewInit () {
        this.init();
    }
    ngOnDestroy () {
        this.animationId && window.cancelAnimationFrame(this.animationId);
    }

    init () {
        const canvas = document.querySelector('#myCanvas') as HTMLCanvasElement;
        this.gl = canvas.getContext('webgl');

        // 初始化 shader
        this.webglService.initShader(this.gl, this.vertexShaderSource, this.fragShaderSource);

        // 初始化 VertexBuffer
        const n = this.initVertexBuffer(this.gl);

        this.tick(this.gl, n);
    }

    private tick (gl: WebGLRenderingContext, n: number) {
        this.render(gl, n);
        this.animationId = window.requestAnimationFrame(() => { this.tick(gl, n)});
    }
    private render (gl: WebGLRenderingContext, n: number) {
        console.log('render');
        // 创建旋转矩阵, 注意 WebGL 中矩阵是列主序的，相当于变换矩阵的转置
        const ANGLE = this.ANGLE;
        this.ANGLE++;
        const radian = Math.PI * ANGLE / 180;
        const cosB = Math.cos(radian), sinB = Math.sin(radian);

        const xformMatrix = new Float32Array([
            cosB,   sinB,   0.0,    0.0,
            -sinB,  cosB,   0.0,    0.0,
            0.0,    0.0,    1.0,    0.0,
            0.0,    0.0,    0.0,    1.0,
        ]);
        const program = this.webglService.getProgramByGLContext(gl);
        const u_xformMatrix = gl.getUniformLocation(program, 'u_xformMatrix');
        gl.uniformMatrix4fv(u_xformMatrix, false, xformMatrix);


        // 设置背景颜色
        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);

        // 画点
        gl.drawArrays(gl.TRIANGLES, 0, n);

    }

    private initVertexBuffer (gl: WebGLRenderingContext) {
        const vertices = new Float32Array([
            //x     y
            0.0,    0.5,
           -0.5,   -0.5,
            0.5,   -0.5
        ]);
        const n = 3;    // 点的个数
        const byteLen = vertices.BYTES_PER_ELEMENT;

        // 创建缓冲区对象
        const vertexBuffer = gl.createBuffer();
        
        // 将缓冲区对象绑定到目标
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

        // 向缓冲区对象中写入数据
        gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

        const program = this.webglService.getProgramByGLContext(gl);
        const a_Position = gl.getAttribLocation(program, 'a_Position');

        // 将缓冲区对象分配给 a_Position 变量
        gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 2 * byteLen, 0);

        // 连接 a_Position 变量与分配给它的缓冲区对象
        gl.enableVertexAttribArray(a_Position);

        return n;
    }
}